package com.example.userlogin.controller;

import com.example.userlogin.dto.*;
import com.example.userlogin.entity.User;
import com.example.userlogin.service.AuthenticationService;
import com.example.userlogin.service.UserAuditService;
import com.example.userlogin.service.UserRegistrationService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 * 职责：处理用户认证相关的HTTP请求
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthenticationService authenticationService;

    @Autowired
    private UserRegistrationService userRegistrationService;

    @Autowired
    private UserAuditService userAuditService;

    /**
     * 用户登录
     */
    @PostMapping("/signin")
    public ResponseEntity<JwtResponse> authenticateUser(
            @Valid @RequestBody LoginRequest loginRequest,
            HttpServletRequest request) {
        
        logger.info("用户登录请求: {}", loginRequest.getUsername());
        
        try {
            // 执行认证
            JwtResponse jwtResponse = authenticationService.authenticateUser(loginRequest);
            
            // 记录登录审计日志
            String ipAddress = getClientIpAddress(request);
            userAuditService.logUserLogin(loginRequest.getUsername(), ipAddress);
            
            logger.info("用户登录成功: {}", loginRequest.getUsername());
            return ResponseEntity.ok(jwtResponse);
            
        } catch (Exception e) {
            // 记录认证失败日志
            String ipAddress = getClientIpAddress(request);
            userAuditService.logAuthenticationFailure(loginRequest.getUsername(), ipAddress, e.getMessage());
            
            logger.warn("用户登录失败: {}, 原因: {}", loginRequest.getUsername(), e.getMessage());
            throw e; // 重新抛出异常，由全局异常处理器处理
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/signup")
    public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
        logger.info("用户注册请求: {}", signUpRequest.getUsername());
        
        // 验证注册请求
        userRegistrationService.validateRegistrationRequest(signUpRequest);
        
        // 执行注册
        User user = userRegistrationService.registerUser(signUpRequest);
        
        logger.info("用户注册成功: {}", user.getUsername());
        return ResponseEntity.ok(new MessageResponse("用户注册成功!"));
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty()) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}